<template>
    <view>
        <!-- 暂无数据 -->
        <view v-if="isShopcarEmpty">
            <image :src="mallimgUrl + 'empty.png'" class="shopcar-empty-icon"></image>
            <view class="shopcar-empty-text text-df">购物车竟然是空的，快去逛逛吧～</view>
            <view class="shopcar-empty-btn text-lg text-center text-white bg-orange radiues"
                @tap.stop.prevent="gotoHome">去首页</view>
        </view>
        <!-- 购物车模块 -->
        <view v-if="!isShopcarEmpty">
            <view class="head_chang text-right text-df text-orange" @tap.stop.prevent="toEdit">
                <view class="padding-right-lg">{{ btnText }}</view>
            </view>
            <view style="height: 90rpx"></view>
            <view class="moudle bg-white margin-lr-sm margin-bottom-sm flexs align-center padding-top flex-wrap"
                :data-goodsid="item.productId" :data-productSn="item.productSn" :data-status="item.status"
                @tap="gotoNext" v-for="(item, index) in goodsList" :key="index">
                <!-- 商品展示 -->

                <view class="flexs align-center padding-bottom-sm">
                    <view class="padding-left-sm padding-right-xs" @tap.stop.prevent="iconclick">
                        <van-checkbox :value="item.checked" checked-color="#FF8722" @change="
                            singleSelect($event, { checked: item.checked, ids: item.id, id: item.productId, skuid: item.productSkuId, type: item.productDistributionType })
                        " :data-checked="item.checked" :data-ids="item.id" :data-id="item.productId"
                            :data-skuid="item.productSkuId" :data-type="item.productDistributionType"></van-checkbox>
                    </view>
                    <view class="p-r">
                        <image class="goodes_img margin-right-sm" v-if="item.pic" :src="item.productPic || item.pic" />
                        <image class="goodes_img margin-right-sm" v-else-if="item.productPic" :src="item.productPic" />
                        <view class="shade" v-if="item.status == 1 || item.status == 2">
                            <text class="down" v-if="item.status == 1">已下架</text>
                            <text class="down" v-if="item.status == 2">暂无库存</text>
                        </view>
                    </view>
                    <!-- <view>规格无库存请重新选择</view> -->
                    <view style="width: 450rpx; height: 180rpx; position: relative">
                        <view class="text-df text-tline">{{ item.productName }}</view>
                        <view class="text-sm text-darkGrey padding-top-xs">{{ item.spType }}</view>
                        <view class="goods_bar flexs align-center justify-between">
                            <view v-if="checkMaker && item.priceMaker" class="text-lg text-price text-red">
                                <text>{{ item.priceMaker }}</text>
                                <text class="text-through text-darkGray padding-left-sm text-sm">
                                    <block v-if="item.updatePrice">{{ item.updatePrice }}</block>
                                    <block v-else>{{ item.price }}</block>
                                </text>
                            </view>
                            <view v-else class="text-lg text-price text-red" style="padding-top: 4rpx">
                                <block v-if="item.updatePrice">{{ item.updatePrice }}</block>
                                <block v-else>{{ item.price }}</block>
                            </view>
                            <view class="flexs align-center text-car">
                                <view class="text-dg text-dd text-gray" @tap.stop.prevent="sub"
                                    :data-num="item.quantity" :data-productId="item.productId"
                                    :data-skuid="item.productSkuId" :data-productCategoryId="item.productCategoryId"
                                    :data-price="item.price" :data-productSkuCode="item.productSkuCode"
                                    :data-id="item.id" :data-goodsType="item.goodsType">
                                    -
                                </view>
                                <view class="amount flexs justify-center align-center">{{ item.quantity }}</view>
                                <view class="text-dg text-dd" @tap.stop.prevent="add" :data-num="item.quantity"
                                    :data-productId="item.productId" :data-skuid="item.productSkuId"
                                    :data-productCategoryId="item.productCategoryId" :data-price="item.price"
                                    :data-productSkuCode="item.productSkuCode" :data-id="item.id"
                                    :data-goodsType="item.goodsType">
                                    +
                                </view>
                            </view>
                            <!-- <van-stepper value="{{item.quantity}}" step="1" bind:change="addBuyNum" data-id="{{item.productId}}" data-skuid="{{item.productSkuId}}"/> -->
                        </view>
                    </view>
                </view>

                <!-- 自提提示语 -->

                <view class="storealign" v-if="item.productDistributionType == 3">亲~可选择上门自提，下单后可出示核销码到门店提取</view>

                <view class="storealign" v-if="item.productDistributionType == 2">亲，此商品仅能上门自提，下单后可出示核销码到门店提货</view>
            </view>
        </view>
        <!-- 猜你喜欢 -->
        <view class="flexs align-center justify-center">
            <view class="goodsdetail-guess-line"></view>
            <view class="text-lg padding-sm text-bold">猜你喜欢</view>
            <view class="goodsdetail-guess-line"></view>
        </view>
        <view class="flexs justify-between padding-lr-sm padding-bottom">
            <view>
                <view class="goods_info radius margin-top-sm bg-white" v-if="index % 2 == 0" :data-goodsid="item.id"
                    :data-productSn="item.productSn" @tap.stop.prevent="gotoNext"
                    v-for="(item, index) in randomGoodsList" :key="index">
                    <view class="p-r">
                        <image class="goods_img" mode="widthFix" :src="item.pic" />
                        <view class="goods_sold padding-lr-sm text-sm text-white" v-if="item.sale">已售: {{ item.sale }}
                        </view>
                    </view>

                    <view class="padding-lr-sm margin-tb-sm text-df text-tline">{{ item.name }}</view>

                    <view class="flexs align-center padding-lr-sm padding-bottom">
                        <view class="text-price text-red text-df text-bold">{{ item.price }}</view>
                        <view v-if="item.originalPrice != null"
                            class="padding-left-sm text-price text-darkGray text-sm text-through">{{
                                item.originalPrice
                            }}</view>
                    </view>
                </view>
            </view>
            <view>
                <view class="goods_info radius margin-top-sm bg-white" v-if="index % 2 == 1" :data-goodsid="item.id"
                    :data-productSn="item.productSn" @tap.stop.prevent="gotoNext"
                    v-for="(item, index) in randomGoodsList" :key="index">
                    <view class="p-r">
                        <image class="goods_img" mode="widthFix" :src="item.pic" />
                        <view class="goods_sold padding-lr-sm text-sm text-white" v-if="item.sale">已售: {{ item.sale }}
                        </view>
                    </view>

                    <view class="padding-lr-sm margin-tb-sm text-df text-tline">{{ item.name }}</view>

                    <view class="flexs align-center padding-lr-sm padding-bottom">
                        <view class="text-price text-red text-df text-bold">{{ item.price }}</view>
                        <view v-if="item.originalPrice != null"
                            class="padding-left-sm text-price text-darkGray text-sm text-through">{{
                                item.originalPrice
                            }}</view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 底部模块 -->
        <view class="goods_list"></view>
        <view class="bar_bottom bg-white flexs align-center padding-lr-lg justify-between box-sizing">
            <block v-if="!editFlag">
                <van-checkbox :value="allCheckFlag" checked-color="#FF8722" @change="selectAllFn">全选</van-checkbox>
                <view class="shopcar-count-btn text-center bg-orange text-white text-df text-bold radiues"
                    @tap.stop.prevent="gotoOrder">去结算({{ selectgoodsNum }})</view>
            </block>
            <block v-if="editFlag">
                <van-checkbox :value="allCheckFlag" checked-color="#FF8722" @change="selectAllFn">全选</van-checkbox>
                <view class="shopcar-count-btn text-center bg-white text-orange text-df text-bold radiues"
                    style="border: 1rpx solid #ff8722" @tap.stop.prevent="delAll">删除</view>
            </block>
        </view>
    </view>
</template>

<script>
import vanIcon from '@/wxcomponents/vant/dist/icon/index';
import vanActionSheet from '@/wxcomponents/vant/dist/action-sheet/index';
import vanSwipeCell from '@/wxcomponents/vant/dist/swipe-cell/index';
import vanStepper from '@/wxcomponents/vant/dist/stepper/index';
import vanCheckbox from '@/wxcomponents/vant/dist/checkbox/index';
const _request = require('../../utils/request.js');

const app = getApp();
export default {
    components: {
        vanIcon,
        vanActionSheet,
        vanSwipeCell,
        vanStepper,
        vanCheckbox
    },
    data() {
        return {
            mallimgUrl: app.globalData.mallimgUrl,
            isShopcarEmpty: true,
            goodsList: [],
            editFlag: false,
            randomGoodsList: [],
            btnText: '编辑',
            allCheckFlag: false,
            selectgoodsNum: 0,
            pageNo: 0,
            pageSize: 20,
            checkMaker: false //是否是创客用户
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getRandomProduct();
    },
    onShow: function () {
        this.setData({
            allCheckFlag: false,
            checkMaker: uni.getStorageSync('maker')?.ismaker || false
        });
        this.queryShopCarInfo();
    },
    methods: {
        toEdit() {
            this.setData({
                editFlag: !this.editFlag
            });
            const text = this.editFlag ? '完成' : '编辑';
            let list = this.goodsList;
            const self = this;
            list.forEach((e) => {
                if (!self.editFlag) {
                    e.checked = false;
                } else {
                    e.activeClass = '';
                }
            });
            this.setData({
                goodsList: list,
                btnText: text
            });

            if (!this.editFlag) {
                this.setData({
                    allCheckFlag: false,
                    selectgoodsNum: 0
                });
            }
        },

        showDel(event) {
            if (this.editFlag) {
                return;
            }

            let list = this.goodsList;
            const self = this;
            list.forEach((e) => {
                if (event.currentTarget.dataset.id == e.id) {
                    if (e.activeClass === 'active-right') {
                        e.activeClass = '';
                    } else {
                        e.activeClass = 'active-right';
                    }
                } else {
                    e.activeClass = '';
                }
            });
            this.setData({
                goodsList: list
            });
        },

        getRandomProduct: function () {
            const that = this;

            _request
                .get(
                    '/mall-product/getRandomProduct',
                    {
                        type: 1,
                        userId: uni.getStorageSync('userId')
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        let list = res.data.data || [];
                        that.setData({
                            randomGoodsList: list
                        });
                    }
                });
        },

        gotoNext: function (item) {
            if (item.currentTarget.dataset.status == 1) {
                uni.showToast({
                    title: '已下架商品无法进入详情页',
                    icon: 'none'
                });
            } else {
                uni.navigateTo({
                    url: '/shopingmall/goodsdetail/goodsdetail' + this.getparams(item.currentTarget.dataset)
                });
            }
        },

        getparams: function (item) {
            const list = [];

            for (const key in item) {
                if (key === 'url') {
                    continue;
                }

                list.push(key + '=' + item[key]);
            }

            if (list.length) {
                return '?' + list.join('&');
            } else {
                return '';
            }
        },

        handleDel(ids) {
            // const self = this
            _request
                .postObj(
                    '/mall-cart-item/batchDel',
                    {
                        ids: ids.join(',') // userId: wx.getStorageSync('userId'),
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    this.getRandomProduct();
                    this.queryShopCarInfo();
                    return; // if (res.data.code === 200) {
                    //   let list = self.data.goodsList || []
                    //   let ind
                    //   list.forEach((e, index) => {
                    //     if (e.id == goodsid) {
                    //       ind = index
                    //     }
                    //   })
                    //   list.splice(index, 1)
                    //   self.setData({
                    //     goodsList: list,
                    //     isShopcarEmpty: list.size() === 0
                    //   })
                    //   self.countSelectGoodsNum()
                    // }
                });
        },

        queryShopCarInfo() {
            const self = this;

            _request
                .get(
                    '/mall-cart-item/list',
                    {
                        // userId: wx.getStorageSync('userId'),
                        offset: this.pageNo,
                        pageSize: this.pageSize
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        let list = res.data.data || [];
                        list.forEach((e) => {
                            e.spObj = JSON.parse(e.specification || '[{"key":"颜色","value":"银色"},{"key":"容量","value":"32G"}]');
                            let list = [];
                            e.spObj.forEach((item) => {
                                list.push(item.key + ':' + item.value);
                            });
                            e.spType = list.join(',');
                            e.checked = false;
                        });
                        self.setData({
                            goodsList: list,
                            isShopcarEmpty: (res.data.data || []).length === 0
                        });

                        if (this.goodsList.length <= 0) {
                            this.setData({
                                allCheckFlag: false
                            });
                        }

                        self.countSelectGoodsNum();
                    }
                });
        },

        add(event) {
            console.log(event);
            const productId = event.currentTarget.dataset.productid;
            const skuId = event.currentTarget.dataset.skuid;
            const num = event.currentTarget.dataset.num;
            const id = event.currentTarget.dataset.id;
            const productCategoryId = event.currentTarget.dataset.productcategoryid;
            const price = event.currentTarget.dataset.price;
            const productskucode = event.currentTarget.dataset.productskucode;
            const goodsType = event.currentTarget.dataset.goodstype;

            _request
                .postObj(
                    '/mall-cart-item/update',
                    {
                        deleteStatus: 0,
                        productId: productId,
                        isPurchase: 0,
                        id: id,
                        productSkuId: skuId,
                        quantity: num + 1,
                        productCategoryId: productCategoryId,
                        productSkuCode: productskucode,
                        price: price,
                        userId: uni.getStorageSync('userId'),
                        type: 1,
                        goodsType: goodsType
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        let list = this.goodsList;
                        list.forEach((e) => {
                            if (e.productId == productId && e.productSkuId == skuId) {
                                if (e.quantity < e.stock) {
                                    e.quantity = e.quantity + 1;
                                    return;
                                } else {
                                    uni.showToast({
                                        title: '库存不足',
                                        icon: 'none'
                                    });
                                    return;
                                }
                            }
                        });
                        this.setData({
                            goodsList: list
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none'
                        });
                    }
                });
        },

        sub(event) {
            const productId = event.currentTarget.dataset.productid;
            const skuId = event.currentTarget.dataset.skuid;
            const num = event.currentTarget.dataset.num;
            const id = event.currentTarget.dataset.id;
            const productCategoryId = event.currentTarget.dataset.productcategoryid;
            const price = event.currentTarget.dataset.price;
            const productskucode = event.currentTarget.dataset.productskucode;
            const goodsType = event.currentTarget.dataset.goodstype;

            if (num > 1) {
                _request
                    .postObj(
                        '/mall-cart-item/update',
                        {
                            deleteStatus: 0,
                            productId: productId,
                            isPurchase: 0,
                            id: id,
                            productSkuId: skuId,
                            quantity: num - 1,
                            productCategoryId: productCategoryId,
                            productSkuCode: productskucode,
                            price: price,
                            userId: uni.getStorageSync('userId'),
                            type: 1,
                            goodsType: goodsType
                        },
                        app.globalData.mallType
                    )
                    .then((res) => {
                        if (res.data.code === 200) {
                            let list = this.goodsList;
                            list.forEach((e) => {
                                if (e.productId == productId && e.productSkuId == skuId) {
                                    e.quantity = e.quantity - 1;
                                }
                            });
                            this.setData({
                                goodsList: list
                            });
                        } else {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                        }
                    });
            }
        },

        gotoHome() {
            uni.switchTab({
                url: '/firstpages/shopping/index'
            });
        },

        singleSelect(event, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(event, _dataset);
            /* ---处理dataset end--- */
            console.log(event);
            const id = event.currentTarget.dataset.id;
            const ids = event.currentTarget.dataset.ids;
            const checked = event.currentTarget.dataset.checked;
            const skuId = event.currentTarget.dataset.skuid;
            const productDistributionType = event.currentTarget.dataset.productDistributionType;
            let list = this.goodsList;

            if (!checked) {
                //选中
                list.forEach((e) => {
                    if (e.productId == id && e.productSkuId == skuId) {
                        e.checked = !e.checked;
                    }
                });
                this.setData({
                    goodsList: list
                });
                this.countSelectGoodsNum();
            } else {
                //取消
                list.forEach((e) => {
                    if (e.productId == id && e.productSkuId == skuId) {
                        e.checked = !e.checked;
                    }
                });
                this.setData({
                    goodsList: list
                });
                this.countSelectGoodsNum();
            }
        },

        countSelectGoodsNum() {
            let selectgoodsNum = 0;
            let list = this.goodsList;
            let checkedList = this.goodsList.map((item) => {
                return item.checked;
            });

            if (checkedList.includes(false) || checkedList.length == 0) {
                this.setData({
                    allCheckFlag: false
                });
            } else {
                this.setData({
                    allCheckFlag: true
                });
            }

            list.forEach((e) => {
                if (e.checked) {
                    selectgoodsNum++;
                }
            });
            this.setData({
                selectgoodsNum: selectgoodsNum
            });
        },

        //全选
        selectAllFn() {
            if (this.goodsList.length <= 0) {
                uni.showToast({
                    title: '暂无商品可以选择',
                    icon: 'none'
                });
                return;
            }

            var allCheckFlag = !this.allCheckFlag;
            this.setData({
                allCheckFlag: allCheckFlag
            });
            let list = this.goodsList;
            const self = this;
            list.forEach((e) => {
                e.checked = self.allCheckFlag;
            });
            this.setData({
                goodsList: list
            });
            this.countSelectGoodsNum();
        },

        delAll() {
            let list = this.goodsList;
            let delList = list.filter((e) => e.checked);

            if (!delList.length) {
                return;
            }

            uni.showModal({
                title: '确定要删除选中商品吗?',
                success: (res) => {
                    if (res.confirm) {
                        let ids = delList.map((e) => e.id);
                        this.handleDel(ids);
                    } else if (res.cancel) {
                    }
                }
            });
            this.countSelectGoodsNum();
        },

        iconclick() { },

        gotoOrder() {
            let list = this.goodsList;
            let delList = list.filter((e) => e.checked);
            let ids = delList.map((e) => e.id); // 购物车id集合

            let distributionType = delList.map((e) => e.distributionType);
            let productDistributionType = delList.map((e) => e.productDistributionType);
            let type = delList.map((e) => e.type);
            let status = delList.map((e) => e.status);

            if (!delList.length) {
                uni.showToast({
                    title: '请选择需要购买的商品',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            if (status.includes('1')) {
                uni.showToast({
                    title: '很抱歉此商品已下架暂时无法购买',
                    icon: 'none'
                });
                return;
            } else if (status.includes('2')) {
                uni.showToast({
                    title: '很抱歉此商品暂无库存请等待平台添加库存',
                    icon: 'none'
                });
                return;
            } else {
                uni.navigateTo({
                    url: '/shopingmall/order/order?ids=' + ids + '&distributionType=' + distributionType + '&type=' + type + '&productDistributionType=' + productDistributionType
                });
            }
        }
    }
};
</script>
<style>
/* 暂无数据 */
.shopcar-empty-icon {
    width: 320rpx;
    height: 298rpx;
    margin: 120rpx auto 32rpx auto;
    display: block;
}

.shopcar-empty-text {
    text-align: center;
    color: #999999;
}

.amount {
    height: 38rpx;
    border-left: 2rpx solid #aaa;
    border-right: 2rpx solid #aaa;
    padding-left: 10rpx;
    padding-right: 10rpx;
}

.shopcar-empty-btn {
    width: 300rpx;
    line-height: 100rpx;
    margin: 50px auto;
}

/* 购物车展示 */
.head_chang {
    position: fixed;
    background-color: #ffffff;
    width: 750rpx;
    line-height: 80rpx;
    z-index: 999;
}

.moudle {
    width: 710rpx;
    box-shadow: 2px 2px 8px 0px rgba(236, 236, 236, 0.4);
}

.goodes_img {
    width: 160rpx;
    height: 180rpx;
}

.shade {
    width: 160rpx;
    height: 180rpx;
    position: absolute;
    top: 0;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
}

.down {
    line-height: 180rpx;
    font-size: 28rpx;
    color: #fff;
}

.goods_bar {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
}

.text-car {
    height: 38rpx;
    border: 2rpx solid #aaa;
    border-radius: 10rpx;
}

.text-dd {
    font-size: 45rpx;
    padding-left: 10rpx;
    padding-right: 10rpx;
}

.storealign {
    width: 710rpx;
    height: 38rpx;
    font-size: 24rpx;
    text-align: center;
    color: #ff8722;
    background: rgb(254, 245, 230);
    padding: 8rpx 0;
    border-radius: 0 0 8rpx 8rpx;
}

/* 猜你喜欢 */
.goodsdetail-guess-line {
    height: 1rpx;
    width: 100rpx;
    background-color: #ff8722;
}

.goods_info {
    width: 340rpx;
    position: relative;
    box-shadow: 2px 4px 8px 0px #f5f5f5;
}

.goods_img {
    width: 340rpx;
    height: 340rpx;
}

.goods_sold {
    position: absolute;
    left: 0;
    bottom: 10rpx;
    line-height: 46rpx;
    border-radius: 0 20rpx 20rpx 0;
    background-color: rgb(0, 0, 0, 0.5);
}

.text-darkGrey {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

/* 底部模块 */
.goods_list {
    padding-bottom: calc(120rpx + env(safe-area-inset-bottom) / 2);
}

.bar_bottom {
    height: calc(100rpx + env(safe-area-inset-bottom) / 2);
    padding-bottom: calc(env(safe-area-inset-bottom) / 2);
    width: 750rpx;
    position: fixed;
    bottom: 0;
    z-index: 999;
}

.shopcar-count-btn {
    width: 200rpx;
    line-height: 60rpx;
}
</style>
